import random

from django.http import JsonResponse
import sqlite3
import datetime
from django.shortcuts import render, redirect
from myapp.models import Customer, Update, User, OrderList


def get_sql(database, sql):
    conn = sqlite3.connect(database)
    cursor = conn.cursor()
    c = cursor.execute(sql).fetchall()
    return c


def topnews(request):
    if request.POST:
        start = int(request.POST['start']) - 1
        len = int(request.POST['len'])
        user = request.session.get('user', 'False')
        database = 'db.sqlite3'
        # sql = 'select id,name,token,number,Create_time,register_time,last_run_time,register_count,run_count from myapp_customer where id between {} and {}'.format(start,start+len-1)
        sql = 'select  name,token,number,substr(Create_time,1,16) as time,substr(Duty_time,1,16) as duty,title from myapp_customer where author="{}" '.format(
            user)
        list = get_sql(database, sql)
        context = {}
        context['list'] = list[start:start + len]
        return JsonResponse(context)
    else:
        pass
def orders(request):
    user = request.session.get('user', 'False')
    list=OrderList.objects.filter(account_from=user)
    orderlist=[]
    for i in list:
        temp=[]
        temp.append(str(i.Create_Time)[0:16])
        temp.append(i.account_to)
        temp.append(i.Cards_type)
        temp.append(i.Cards_Count)
        temp.append(i.Money)
        orderlist.append(temp)
    context={'list':orderlist}
    return JsonResponse(context)


def identification(request):
    if request.POST:
        context ={}
        token = request.POST['token']
        id = request.POST['id']
        list = Customer.objects.filter(token=token)
        update = Update.objects.filter(type='latest')
        context ={}
        context['version'] = update[0].version
        context['data1'] =token
        context['data2'] =id
        if list:
            if list[0].number == id:
                i = list[0]
                thetime=str(i.Duty_time)[:19]
                dutytime=datetime.datetime.strptime(thetime,'%Y-%m-%d %H:%M:%S')
                if (dutytime-datetime.datetime.now()).days>=0:
                    context['token'] = i.token
                    context['name'] = i.name
                    context['number'] = i.number
                    context['title'] = i.title
                    context['time'] = thetime
                    i.run_count += 1
                    i.last_run_time = datetime.datetime.now()
                    i.save()
                    context['resultcode'] = 200
                    context['message'] = '恭喜发财！'
                else:
                    context['resultcode'] = 100
                    context['message'] ='此注册码已过期'
            else:
                context['resultcode'] = 100
                context['message'] = '此注册码未绑定此手机'
        else:
            context['resultcode'] = 100
            context['message'] ='此注册码不存在'
        return JsonResponse(context)


def register(request):
    if request.POST:
        token = request.POST['token']
        id = request.POST['id']
        list = Customer.objects.filter(token=token)
        title_list={'试用':1,'周卡':7,'月卡':30,'永久':999}
        if list:
            if list[0].number == '':
                list[0].number = id
                list[0].register_count += 1
                list[0].register_time = datetime.datetime.now()
                if(list[0].Duty_time is None):
                    list[0].Duty_time = datetime.datetime.now() + datetime.timedelta(days=title_list[list[0].title])
                list[0].save()
                context = {'resultcode': 200, 'data1': token, 'data2': id,'message': '可以开始运行啦'}
            elif list[0].number == id:
                context = {'resultcode': 100, 'data1': token, 'data2': id, 'message': '已经注册过啦，直接运行吧'}
            else:
                context = {'resultcode': 100, 'data1': token, 'data2': id, 'message': '此注册码未绑定此手机'}
        else:
            context = {'resultcode': 100, 'data1': token, 'data2': id, 'message': '此注册码不存在'}
        return JsonResponse(context)


def cancel(request):
    if request.POST:
        token = request.POST['token']
        id = request.POST['id']
        list = Customer.objects.filter(token=token)
        if list:
            if list[0].number == id:
                list[0].number = ''
                list[0].cancel_time = datetime.datetime.now()
                list[0].save()
                context = {'resultcode': 200, 'data1': token, 'data2': id, 'message': '可以在其他手机上绑定啦'}
            else:
                context = {'resultcode': 100, 'data1': token, 'data2': id, 'message': '此注册码不属于本手机'}
        else:
            context = {'resultcode': 100, 'data1': token, 'data2': id, 'message': '此注册码不存在'}
        return JsonResponse(context)
def admincancel(request):
    context={}
    if request.POST:
        token = request.POST['token']
        user = request.session.get('user', 'False')
        list = Customer.objects.filter(token=token)
        if list:
            if user == 'dundun' or user == 'liuxu' or user=='liuyang':
                list[0].number= ''
                list[0].save()
                context = {'message': '解绑成功'}
            else:
                context = {'message': '无权限解绑注册码'}
        else:
            context={'message': '此注册码不存在'}
    return JsonResponse(context)
def addtime(request):
    context={}
    if request.POST:
        title_list={'1':'试用','7':'周卡','30':'月卡','999':'永久'}
        cards_list={'1':'testcard','7':'weekcard','30':'monthcard','999':'foevercard'}
        token = request.POST['token']
        type = request.POST['type']
        user = request.session.get('user', 'False')
        person=User.objects.filter(account=user)[0]
        list = Customer.objects.filter(token=token)
        cards = getattr(person, cards_list[type])
        if list:
            if cards>0:
                setattr(person, cards_list[type], cards-1)
                person.save()
                list[0].Duty_time +=datetime.timedelta(days=int(type))
                try:
                    list[0].save()
                    Order = OrderList(account_from=user, account_to='续费',Cards_type=title_list[type],Cards_Count=1)
                    Order.save()
                    context = {'message': '续费成功'}
                except:
                    context = {'message': '续费失败'}
            else:
                context = {'message': '对不起，您没有足够的配额，请找管理员充值！'}
        else:
            context = {'message': '此注册码不存在'}
    return JsonResponse(context)

def createone(request):
    context={}
    if request.POST:
        title_list={'1':'试用','7':'周卡','30':'月卡','999':'永久'}
        cards_list={'1':'testcard','7':'weekcard','30':'monthcard','999':'foevercard'}
        token = request.POST['token']
        version = request.POST['version']
        name = request.POST['name']
        type = request.POST['type']
        money=int(request.POST['money'])
        token=version+token
        user = request.session.get('user', 'False')
        person=User.objects.filter(account=user)[0]
        if version in person.versionstring:
            cards=getattr(person,cards_list[type])
            list = Customer.objects.filter(token=token)
            if not list:
                if cards>0:
                    setattr(person, cards_list[type], cards-1)
                    person.save()
                    add = Customer(token=token, name=name, author=user,title=title_list[type])
                    try:
                        add.save()
                        Order = OrderList(account_from=user, Cards_type=title_list[type],Cards_Count=1, Money=money)
                        Order.save()
                        context = {'message': '添加成功，您的注册码为'+token}
                    except:
                        context = {'message': '添加失败'}
                else:
                    context = {'message': '对不起，您没有足够的配额，请找管理员充值！'}
            else:
                context = {'message': '此注册码已存在'}
        else:
            context = {'message': '对不起，您没有权限创建此类注册码，请联系管理员！'}
    return JsonResponse(context)
def createmore(request):
    if request.POST:
        title_list={'1':'试用','7':'周卡','30':'月卡','999':'永久'}
        cards_list={'1':'testcard','7':'weekcard','30':'monthcard','999':'foevercard'}
        user = request.session.get('user', 'False')
        version = request.POST['version']
        count = int(request.POST['count'])
        name = request.POST['name']
        type = request.POST['type']
        try:
            money=int(request.POST['money'])
        except:
            context={'user':'对不起，','message':'金额填写错误，请重新填写！'}
            return render(request, 'welcome.html', context)
        person=User.objects.filter(account=user)[0]
        if version in person.versionstring:
            cards=getattr(person,cards_list[type])
            token_list=[]
            num=count
            if cards >=count&count>0:
                setattr(person, cards_list[type], cards-count)
                person.save()
                while(count>0):
                    s = version
                    for j in range(10):
                        x = random.randint(0, 8)
                        s = s + str(x)
                    list = Customer.objects.filter(token=s)
                    if not list:
                        add = Customer(token=s, name=name, author=user,title=title_list[type])
                        add.save()
                        token_list.append(s)
                        count-=1
                Order = OrderList(account_from=user, Cards_type=title_list[type], Cards_Count=num, Money=money)
                Order.save()
                context={'list':token_list,'title':title_list[type],'num':num}
                return render(request, 'tokens.html', context)
            context={'user':'对不起，','message':'您没有足够的配额，请找管理员充值！'}
        else:
            context={'user':'对不起，','message':'您没有权限创建此类注册码，请联系管理员！'}
    return render(request, 'welcome.html', context)
def createindex(request):
    if request.POST:
        title_list={'1':'试用','7':'周卡','30':'月卡','999':'永久'}
        cards_list={'1':'testcard','7':'weekcard','30':'monthcard','999':'foevercard'}
        version = request.POST['version']
        diycode = request.POST['diycode']
        count = int(request.POST['count'])
        name = request.POST['name']
        type = request.POST['type']
        try:
            money=int(request.POST['money'])
        except:
            context={'user':'对不起，','message':'金额填写错误，请重新填写！'}
            return render(request, 'welcome.html', context)
        user = request.session.get('user', 'False')
        person=User.objects.filter(account=user)[0]
        if version in person.versionstring:
            cards=getattr(person,cards_list[type])
            token_list=[]
            num=count
            if cards >=count&count>0:
                setattr(person, cards_list[type], cards-count)
                person.save()
                while(count>0):
                    s = version+diycode
                    x = str(count)
                    s = s + str(x)
                    list = Customer.objects.filter(token=s)
                    if not list:
                        add = Customer(token=s, name=name, author=user,title=title_list[type])
                        add.save()
                        token_list.append(s)
                        count-=1
                Order = OrderList(account_from=user, Cards_type=title_list[type], Cards_Count=num, Money=money)
                Order.save()
                context={'list':token_list,'title':title_list[type],'num':num}
                return render(request, 'tokens.html', context)
            context = {'user': '对不起，', 'message': '您没有足够的配额，请找管理员充值！'}
        else:
            context={'user':'对不起，','message':'您没有权限创建此类注册码，请联系管理员！'}
    return render(request, 'welcome.html', context)
def transfer(request):
    context={}
    if request.POST:
        title_list={'1':'试用','7':'周卡','30':'月卡','999':'永久'}
        cards_list={'1':'testcard','7':'weekcard','30':'monthcard','999':'foevercard'}
        count = int(request.POST['count'])
        id = int(request.POST['id'])
        type = request.POST['type']
        money=int(request.POST['money'])
        user = request.session.get('user', 'False')
        person=User.objects.filter(account=user)[0]
        cards=getattr(person,cards_list[type])
        if cards>=count:
            toperson=User.objects.filter(id=id)[0]
            tocards=getattr(toperson,cards_list[type])
            cards-=count
            tocards+=count
            setattr(person, cards_list[type], cards)
            setattr(toperson, cards_list[type], tocards)
            person.save()
            toperson.save()
            Order=OrderList(account_from=user,account_to=toperson.account,Cards_type=title_list[type],Cards_Count=count,Money=money)
            Order.save()
            context = {'message': '转让成功'}
        else:
            context = {'message': '您没有足够的配额，请找管理员充值！'}
    return JsonResponse(context)




def updatastatus(request):
    context = {}
    list = Update.objects.filter(type='latest')
    if list:
        context['version']=list[0].version
        context['type']=list[0].type
        context['force']=list[0].force
        context['detial']=list[0].detial
    return JsonResponse(context)
